package db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mads Nielsen <k4emic@gmail.com>
 */
abstract class ObjectDAO implements IObjectDAO {
    
    protected boolean loadRelated = false;
    
    public DBConnection getConnection() {
        return DBConnection.getInstance();
    }
    
    protected PreparedStatement prepareStatement(String sql) {
        try {
            
            DBConnection conn = getConnection();
            Connection con = conn.getConnection();
            PreparedStatement pstmt = con.prepareStatement(sql);
            
            return pstmt;
        } catch (SQLException ex) {
            Logger.getLogger(ItemDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }

    public boolean getLoadRelated() {
        return loadRelated;
    }
    
    public void setLoadRelated(boolean loadRelated) {
        this.loadRelated = loadRelated;
    }
    
    protected void bindStatementParams(PreparedStatement pstmt, Object[] params) throws SQLException {
        int parameterIndex = 1;
            for (Object param : params) {

                Class<?> paramClass = param.getClass();

                if (paramClass == java.lang.String.class) {
                    pstmt.setString(parameterIndex, param.toString());
                } else if (paramClass == java.lang.Integer.class) {
                    pstmt.setInt(parameterIndex, (Integer) param);
                } else if (paramClass == java.lang.Double.class
                        || paramClass == java.lang.Float.class) {
                    pstmt.setDouble(parameterIndex, (Double) param);
                }

                parameterIndex++;
            }
    }
    
    protected void startTransaction() throws SQLException {
        getConnection().getConnection().setAutoCommit(false);
    }
    
    protected void rollbackTransaction() throws SQLException {
        getConnection().getConnection().rollback();
    }
    
    protected void commitTransaction() throws SQLException {
        getConnection().getConnection().commit();
        getConnection().getConnection().setAutoCommit(true);
    }
    
}
